using System;
using System.Threading.Tasks;

namespace ENodeMicro.Common.Helpers
{
    /// <summary>
    /// 命令帮助方法
    /// </summary>
    public static class CommandHelper
    {
        /// <summary>
        /// [异步]命令执行结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func">需要执行的方法</param>
        /// <param name="onError">发生错误时触发的方法</param>
        /// <returns></returns>
        public static async Task<APIResult<T>> CommandResultAsync<T>(Func<Task<APIResult<T>>> func, Action<string> onError = null) where T : class
        {
            var rsp = new APIResult<T>();
            try
            {
                var result = await func();
                rsp.StatusCode = result.StatusCode;// 状态码
                rsp.Message = result.Message; // 信息
                rsp.Success = result.Success; // 是否成功
                rsp.Data = result.Data; // 数据集
            }
            catch (Exception ex)
            {
                rsp.StatusCode = 500;
                rsp.Message = ex.Message;
                if (ex.InnerException != null) onError?.Invoke(ex.InnerException.Message);
            }
            return rsp;
        }
        /// <summary>
        /// 命令执行结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func">需要执行的方法</param>
        /// <param name="onError">发生错误时触发的方法</param>
        /// <returns></returns>
        public static APIResult<T> CommandResult<T>(Func<APIResult<T>> func, Action<string> onError = null) where T : class
        {
            var rsp = new APIResult<T>();
            try
            {
                var result = func();
                rsp.StatusCode = result.StatusCode;// 状态码
                rsp.Message = result.Message; // 信息
                rsp.Success = result.Success; // 是否成功
                rsp.Data = result.Data; // 数据集
            }
            catch (Exception ex)
            {
                rsp.StatusCode = 500;
                rsp.Message = ex.Message;
                if (ex.InnerException != null) onError?.Invoke(ex.InnerException.Message);
            }
            return rsp;
        }
    }
}